﻿using DevExpress.XtraEditors;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;

namespace LanMessenger
{
    public partial class LanMain : Form
    {
        public LanMain()
        {
            InitializeComponent();
        }
        #region 实例化类对象及公共变量
        private Thread myThread;
        string StartIPAddress = "";
        string EndIPAddress = "";
        int intStrat = 0;  //开始扫描地址
        int intEnd = 0;    //终止扫描地址
        string strIP = "";
        string strflag = "";   //扫描到的IP地址
        #endregion

        #region 定义委托
        /// <summary>
        /// 定义一个更新进度条最大值的委托
        /// </summary>
        /// <param name="x"></param>
        public delegate void D_UpFileSendProgressMax(int x);

        /// <summary>
        /// 定义一个更新发包数量的委托
        /// </summary>
        /// <param name="msg"></param>
        public delegate void D_UpSendBagNu(string msg);


        /// <summary>
        /// 定义一个获取文件MD5值的委托
        /// </summary>
        /// <param name="MD5filePath"></param>
        /// <returns></returns>
        public delegate string D_MyGetMD5(string MD5filePath);

        /// <summary>
        /// 定义更新进度条委托
        /// </summary>
        /// <param name="x"></param>
        public delegate void FileSendProgressB(int x);

        /// <summary>
        /// 定义一个UI控件更新委托 
        /// </summary>
        /// <param name="str"></param>
        public delegate void MyInvoke(string str);

        /// <summary>
        /// 
        /// </summary>
        /// <param name="IP">服务器IP地址</param>
        /// <param name="Port">服务器端口</param>
        /// <param name="FilePath">发送文件的路径</param>
        /// <param name="PackSize">包的大小</param>
        /// <param name="LastPackSize">最后一个包的大小</param>
        /// <param name="PackCount">包的数量</param>
        /// <param name="FileName">文件名</param>
        /// <param name="FileSize">文件大小</param>
        public delegate void D_StartSendFIle(bool Sate, string IP, string Port, string FilePath, string PackSize, string LastPackSize, string PackCount, string FileName, string FileSize);

        /// <summary>
        /// 定义一个委托更新Log
        /// </summary>
        /// <param name="msg"></param>
        public delegate void D_UpMsgLog(string msg);

        /// <summary>
        /// 定义一个委托发送按钮可以使用
        /// </summary>
        public delegate void D_SendBtState(bool state);
        /// <summary>
        /// 定义监听函数委托
        /// </summary>
        public delegate void D_ThreadRec();

        /// <summary>
        /// 定义利用委托显示界面信息
        /// </summary>
        /// <param name="str"></param>
        public delegate void D_UpdateUI_Log(string str);

        #endregion

        #region 公共变量
        /// <summary>
        /// 是否监听
        /// </summary>
        private bool isLis;
        /// <summary>
        /// 定义一个连接
        /// </summary>
        Socket ServerSocket;
        /// <summary>
        /// 定义打开的文件对象
        /// </summary>
        private System.IO.FileInfo fileInfo;
        /// <summary>
        /// 定义包的个数
        /// </summary>
        //private Int32 _bagCount;

        /// <summary>
        /// 判断是否继续进行连接检测
        /// </summary>
        private bool CheckConnection = false;
        #endregion
        /// <summary>
        /// 定义个一个属性来修改ListBox_LogMsg控件，显示信息
        /// </summary>
        public string SetListBoxMsg
        {
            set
            {
                this.ListBox_LogMsg.Items.Add(value);
                ListBox_LogMsg.TopIndex = ListBox_LogMsg.Items.Count - 1;
            }
        }


        /// <summary>
        /// 发送文件设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bt_FileSendConfig_Click(object sender, EventArgs e)
        {
            frm_SendFileConfig sda = new frm_SendFileConfig();
            sda.ShowDialog();
        }
        /// <summary>
        /// 启动定时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bt_TimeStart_Click(object sender, EventArgs e)
        {
            MsgLog.Items.Add("10秒后开始连接服务器!");
            CheckConnection = true;
            bt_TimeStop.Enabled = true;
            bt_TimeStart.Enabled = false;
            StartLinsts();
        }
        /// <summary>
        /// 选择要发送的文件   --浏览
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bt_BrowserFile_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                Text_FileMD5.Text = "";
                string FilePath = openFileDialog1.FileName;
                Text_FilePath.Text = FilePath;
                Text_FileName.Text = System.IO.Path.GetFileName(FilePath);
                //创建文件流
                fileInfo = new System.IO.FileInfo(FilePath);

                //获取文件大小
                Text_FileSize.Text = fileInfo.Length.ToString();

                //获取文件包个数(文件总数除以包的大小)
                Text_PackCount.Text = Convert.ToInt32(fileInfo.Length / (long)Text_PackSize.Value).ToString();
                //Text_PackCount.Text = _bagCount.ToString();

                //获取最后一个文件包大小
                Text_LastPackSize.Text = (fileInfo.Length - Convert.ToInt32(Text_PackCount.Text.Trim()) * (long)Text_PackSize.Value).ToString();

                //获取文件的MD5值
                //Text_FileMD5.Text = NetClassLibrary.FileTools.GetFileMD5(FilePath);

                //使用委托来创建新的线程计算文件MD5值；并传递文件路径和返回MD5值
                label20.Text = "正在计算文件MD5值...";
                FileTools _fileMD5 = new FileTools();
                D_MyGetMD5 myMD5 = new D_MyGetMD5(_fileMD5.GetFileMD5);
                myMD5.BeginInvoke(FilePath, new AsyncCallback(OutMD5), null);
            }
        }
        /// <summary>
        /// 开始发送
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bt_SendFile_Click(object sender, EventArgs e)
        {

            if (System.IO.File.Exists(Text_FilePath.Text))
            {
                //FileSendThread_Class _SendFile = new FileSendThread_Class();
                D_StartSendFIle my_D_StartSendFIle = new D_StartSendFIle(StartSendFile);
                //调用文件发送函数
                my_D_StartSendFIle.BeginInvoke(true, Text_ChlintIP.Text, Text_CientPort.Value.ToString(), Text_FilePath.Text, Text_PackSize.Value.ToString(), Text_LastPackSize.Text, Text_PackCount.Text.Trim().ToString(), Text_FileName.Text, Text_FileSize.Text, null, null);

                bt_SendFile.Enabled = false;
            }
            else
            {
                MyInvoke _myInvoke = new MyInvoke(UpMsgLog);
                BeginInvoke(_myInvoke, new object[] { "ERROR:" + Text_FilePath.Text + "文件不存在!" });

            }
        }
        /// <summary>
        /// 文件发送函数
        /// </summary>
        /// <param name="IP"></param>
        /// <param name="Port"></param>
        /// <param name="FilePath"></param>
        /// <param name="PackSize"></param>
        /// <param name="LastPackSize"></param>
        /// <param name="PackCount"></param>
        public void StartSendFile(bool Sate, string IP, string Port, string FilePath, string PackSize, string LastPackSize, string PackCount, string FileName, string FileSize)
        {
            try
            {
                //设置进度条
                if (Sate == true)
                {

                    if (Convert.ToInt32(PackCount) > 0)
                    {
                        D_UpFileSendProgressMax _D_UpFileSendProgressMax = new D_UpFileSendProgressMax(UpFileSendProgressMax);
                        this.BeginInvoke(_D_UpFileSendProgressMax, new object[] { Convert.ToInt32(PackCount) });
                    }
                    else
                    {
                        D_UpFileSendProgressMax _D_UpFileSendProgressMax = new D_UpFileSendProgressMax(UpFileSendProgressMax);
                        this.BeginInvoke(_D_UpFileSendProgressMax, new object[] { 1 });
                    }

                }
                //指向远程服务器
                IPEndPoint iped = new IPEndPoint(IPAddress.Parse(IP), int.Parse(Port));
                //创建套接字
                Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //连接到远程服务器
                client.Connect(iped);

                IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;

                //MsgLog.Items.Add();

                D_UpMsgLog _D_UpMsgLog = new D_UpMsgLog(UpMsgLog);
                this.BeginInvoke(_D_UpMsgLog, new object[] { System.DateTime.Now.ToString() + ":发送文件【" + FileName + "】->[" + clientep.Address.ToString() + "]" });

                //发送文件名
                LanMessenger.TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(FileName));
                //发送文件大小
                LanMessenger.TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(FileSize));
                //发送包的大小
                LanMessenger.TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(PackSize));
                //发送包的数量
                LanMessenger.TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(PackCount));
                //发送最后一个包的大小
                LanMessenger.TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(LastPackSize));
                //发送文件MD5值
                //NetClassLibrary.TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(Text_FileMD5.Text.ToString()));


                System.IO.FileInfo tmp_FileInfo = new System.IO.FileInfo(FilePath);


                //打开文件
                System.IO.FileStream _fileStream = tmp_FileInfo.OpenRead();

                //定义数据包
                byte[] SendbagData = new byte[Convert.ToInt32(Text_PackSize.Value)];

                //开始循环发送数据包
                for (int i = 0; i < Convert.ToInt32(PackCount); i++)
                {
                    //从文件流中读取指定大小的数据，并填充到SendbagData字节变量中
                    _fileStream.Read(SendbagData, 0, SendbagData.Length);

                    //发送读取的数据包
                    LanMessenger.TransferFiles.SendVarData(client, SendbagData);


                    if (Sate == true)
                    {
                        //更新发包的数量(文本框中显示)
                        D_UpSendBagNu _D_UpSendBagNu = new D_UpSendBagNu(UpSendBagNu);
                        this.BeginInvoke(_D_UpSendBagNu, new object[] { (i + 1).ToString() });

                        //更新进度条
                        FileSendProgressB B = new FileSendProgressB(UpB);
                        this.BeginInvoke(B, new object[] { i + 1 });
                    }
                }

                if (Convert.ToInt32(LastPackSize) != 0)
                {
                    //读取最后一个包
                    SendbagData = new byte[Convert.ToInt32(Convert.ToInt32(LastPackSize))];
                    //发送最后一个包
                    _fileStream.Read(SendbagData, 0, SendbagData.Length);
                    LanMessenger.TransferFiles.SendVarData(client, SendbagData);


                    if (Sate == true)
                    {
                        if (Convert.ToInt32(PackCount) == 0)
                        {
                            //更新进度条
                            FileSendProgressB B = new FileSendProgressB(UpB);
                            this.BeginInvoke(B, new object[] { 1 });
                        }
                    }

                }


                MyInvoke _myInvoke = new MyInvoke(UpMsgLog);
                BeginInvoke(_myInvoke, new object[] { System.DateTime.Now.ToString() + ":【" + FileName + "】发送完成！" });


                //发送文件MD5值
                // NetClassLibrary.TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(Text_FileMD5.Text.ToString()));

                //关闭读取的文件


                _fileStream.Close();

                //关闭网络连接
                client.Close();

                D_SendBtState _D_SendBtState = new D_SendBtState(SendBtState);
                this.BeginInvoke(_D_SendBtState, new object[] { true });
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message);
            }
        }
        #region 利用委托在UI界面上显示内容

        /// <summary>
        /// 设置发送安装状态
        /// </summary>
        public void SendBtState(bool state)
        {
            bt_SendFile.Enabled = state;
        }



        /// <summary>
        /// 定义一个用于显示返回值的函数
        /// </summary>
        /// <param name="result"></param>
        public void OutMD5(IAsyncResult result)
        {
            AsyncResult async = (AsyncResult)result;

            D_MyGetMD5 Deletget = (D_MyGetMD5)async.AsyncDelegate;

            ////把文件的MD5值显示在文本框中
            //Text_FileMD5.Text = Deletget.EndInvoke(result);

            //实例化界面更新委托，调用界面跟新函数更新MD5显示文本框
            MyInvoke mi = new MyInvoke(UpText);
            this.BeginInvoke(mi, new object[] { Deletget.EndInvoke(result) });
        }

        /// <summary>
        /// 更新MD5文本框函数
        /// </summary>
        /// <param name="MD5str"></param>
        public void UpText(string MD5str)
        {
            Text_FileMD5.Text = MD5str;
            label20.Text = "";
        }


        /// <summary>
        /// 更新Log内容显示
        /// </summary>
        /// <param name="msg"></param>
        public void UpMsgLog(string msg)
        {
            MsgLog.Items.Add(msg);
            MsgLog.TopIndex = MsgLog.Items.Count - 1;
            if (MsgLog.Items.Count > 200)
            {
                MsgLog.Items.Clear();
            }
        }

        /// <summary>
        /// 更新进度条
        /// </summary>
        /// <param name="x"></param>
        public void UpB(int x)
        {
            FileSendProgress.Value = x;
        }

        /// <summary>
        /// 定义更新进度条最大值
        /// </summary>
        /// <param name="x"></param>
        public void UpFileSendProgressMax(int x)
        {
            FileSendProgress.Maximum = x;
        }
        #endregion
        /// <summary>
        /// 更新发包数量
        /// </summary>
        /// <param name="msg"></param>
        public void UpSendBagNu(string msg)
        {
            Text_SendBagNumber.Text = msg;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            //获取计算机当前时间
            int intHour = DateTime.Now.Hour;
            int intMinute = DateTime.Now.Minute;
            int intSecond = DateTime.Now.Second;

            //获取设定的时间
            int _intHour = Convert.ToInt32(Text_Time_Hour.Value);
            int _intMinute = Convert.ToInt32(Text_Time_Minute.Value);
            int _intSecond = Convert.ToInt32(Text_Time_Second.Value);

            if (intHour == _intHour && intMinute == _intMinute && intSecond == _intSecond)
            {



                string XmlFilePath = Application.StartupPath + "\\FilePath.xml";

                if (System.IO.File.Exists(XmlFilePath))
                {

                    //创建XML实例
                    XmlDocument xmlDoc = new XmlDocument();
                    //加载XML文件
                    xmlDoc.Load(XmlFilePath);
                    //选择一个匹配的节点
                    XmlNode xn = xmlDoc.SelectSingleNode("FileLists");
                    //获取这个节点的所有子节点
                    XmlNodeList xnl = xn.ChildNodes;

                    string[,] datalist = new string[xnl.Count, 2];
                    //循环读取所有子节点，并显示节点的信息
                    foreach (XmlNode xnf in xnl)
                    {
                        XmlElement xe = (XmlElement)xnf;

                        //想ListView中添加数据
                        //ListViewItem p = new ListViewItem();
                        //p = new ListViewItem(new string[] { xe.GetAttribute("FileName"), xe.GetAttribute("FilePath") });
                        if (System.IO.File.Exists(xe.GetAttribute("FilePath")))
                        {

                            System.IO.FileInfo fi = new System.IO.FileInfo(xe.GetAttribute("FilePath"));

                            //文件包数量
                            string tmp_BagCount = Convert.ToInt32(fi.Length / (long)Text_PackSize.Value).ToString();
                            //最后一个包的大小
                            string tmp_LastBagSize = (fi.Length - Convert.ToInt32(tmp_BagCount) * (long)(Text_PackSize.Value)).ToString();

                            D_StartSendFIle my_D_StartSendFIle = new D_StartSendFIle(StartSendFile);
                            my_D_StartSendFIle.BeginInvoke(
                                                            false,
                                                            Text_ChlintIP.Text,
                                                            Text_CientPort.Value.ToString(),
                                                            xe.GetAttribute("FilePath"),
                                                            Text_PackSize.Value.ToString(),
                                                            tmp_LastBagSize,
                                                            tmp_BagCount,
                                                            xe.GetAttribute("FileName"),
                                                            fi.Length.ToString(),
                                                            null,
                                                            null
                                                            );
                        }
                        else
                        {
                            MyInvoke _myInvoke = new MyInvoke(UpMsgLog);
                            BeginInvoke(_myInvoke, new object[] { "ERROR:" + xe.GetAttribute("FilePath") + "文件不存在!" });

                        }
                    }
                }
            }
        }
        private bool ConnState = false;
        /// <summary>
        /// 开始监听并发送
        /// </summary>
        public void StartLinsts()
        {
            isconnect();

            if (ConnState == true)
            {

                //设置时间间隔为1秒钟执行一次
                timer1.Interval = 1000;

                timer1.Enabled = true;
                MsgLog.Items.Add("已连接到服务器" + Text_ChlintIP.Text + ":" + Text_CientPort.Value.ToString());
                MsgLog.Items.Add(System.DateTime.Now.ToString() + "定时器已经启动！");
                MsgLog.Items.Add("在" + Text_Time_Hour.Value.ToString() + "点" + Text_Time_Minute.Value.ToString() + "分" + Text_Time_Second.Value.ToString() + "秒开始传输！");
                bt_TimeStop.Enabled = true;
                bt_FileSendConfig.Enabled = false;
                bt_TimeStart.Enabled = false;
                Text_Time_Hour.Enabled = false;
                Text_Time_Minute.Enabled = false;
                Text_Time_Second.Enabled = false;
            }
            else
            {

                //MyInvoke _myInvoke = new MyInvoke(UpMsgLog);
                //BeginInvoke(_myInvoke, new object[] { System.DateTime.Now.ToString() + System.DateTime.Now.ToShortTimeString() + "无法连接远程计算机，正在进行重试或请检查IP地址及端口号是否正确！" });


                //MsgLog.Items.Add(System.DateTime.Now.ToShortTimeString() + "无法连接远程计算机，正在进行重试或请检查IP地址及端口号是否正确！");
                //Thread.Sleep(9000);
                StartLinsts();

            }
        }
        /// <summary>
        /// 判断服务器是否开放
        /// </summary>
        /// <returns>True为已连接，False为远程服务器不可用</returns>
        private void isconnect()
        {
            //系统等待1秒钟后开始执行
            DateTime d = DateTime.Now;
            while ((DateTime.Now - d).TotalMilliseconds <= 10000)
            {
                Thread.Sleep(100);//加上这句可以减少系统资源消耗。不知道为什么
                Application.DoEvents();
            }

            if (CheckConnection == true)
            {
                try
                {
                    //指向远程服务器
                    IPEndPoint iped = new IPEndPoint(IPAddress.Parse(Text_ChlintIP.Text.Trim()), int.Parse(Text_CientPort.Text.Trim().ToString()));
                    //创建套接字
                    Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    //连接到远程服务器

                    client.Connect(iped);
                    client.Close();
                    //return true;
                    ConnState = true;

                }
                catch (Exception ex)
                {
                    MyInvoke _myInvoke = new MyInvoke(UpMsgLog);
                    BeginInvoke(_myInvoke, new object[] { System.DateTime.Now.ToString() + ex.Message + "   10秒后重试！" });

                    //MsgLog.Items.Add();
                    //return false;
                    ConnState = false;
                }
            }
        }
        /// <summary>
        /// 暂停发送
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bt_TimeStop_Click(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            bt_FileSendConfig.Enabled = true;
            bt_TimeStart.Enabled = true;
            Text_Time_Hour.Enabled = true;
            Text_Time_Minute.Enabled = true;
            Text_Time_Second.Enabled = true;

            CheckConnection = false;
            bt_TimeStart.Enabled = true;
            bt_TimeStop.Enabled = false;

            MsgLog.Items.Add(System.DateTime.Now.ToString() + ":停止了定时发送！");
        }
        /// <summary>
        /// 启动定时启动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AutoStart_bt_CheckedChanged(object sender, EventArgs e)
        {
            if (AutoStart_bt.Checked)
            {
                try
                {
                    MsgLog.Items.Add("【" + System.DateTime.Now.ToString() + "】" + "正在配置开机自动启动...");
                    //设置开机启动参数
                    XmlDocument doc = new XmlDocument();
                    XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "GB2312", null); doc.AppendChild(dec);  //创建一个根节点（一级）  

                    XmlElement root = doc.CreateElement("ConfigInfo");
                    doc.AppendChild(root);

                    //自动启动状态
                    XmlElement AuotStart = doc.CreateElement("AutoStart");
                    AuotStart.SetAttribute("State", "True");
                    root.AppendChild(AuotStart);

                    //服务端IP
                    XmlElement ServerIP = doc.CreateElement("ServerIP");
                    ServerIP.SetAttribute("IP", Text_ChlintIP.Text);
                    root.AppendChild(ServerIP);

                    //服务端IP
                    XmlElement ServerPort = doc.CreateElement("ServerPort");
                    ServerPort.SetAttribute("Port", Text_CientPort.Value.ToString());
                    root.AppendChild(ServerPort);

                    //设置发送时间(小时)
                    XmlElement PostH = doc.CreateElement("PostH");
                    PostH.SetAttribute("Hour", Text_Time_Hour.Value.ToString());
                    root.AppendChild(PostH);

                    //设置发送时间(分钟)
                    XmlElement PostM = doc.CreateElement("PostM");
                    PostM.SetAttribute("Minute", Text_Time_Minute.Value.ToString());
                    root.AppendChild(PostM);

                    //设置发送时间(秒)
                    XmlElement PostS = doc.CreateElement("PostS");
                    PostS.SetAttribute("Second", Text_Time_Second.Value.ToString());
                    root.AppendChild(PostS);


                    //保存配置文件
                    doc.Save(Application.StartupPath + "\\AutoStartConfig.xml");

                    //获取程序的完整路径
                    string dir = System.Windows.Forms.Application.ExecutablePath;

                    //设置开启启动
                    RegistryKey akey = Registry.LocalMachine;
                    akey = akey.OpenSubKey(@"SOFTWARE\Microsoft\windows\CurrentVersion\Run", true);
                    akey.SetValue("NetClient", dir);
                    akey.Close();
                    AutoStart_bt.Checked = true;

                    MsgLog.Items.Add("【" + System.DateTime.Now.ToString() + "】" + "开启启动配置成功.");
                }
                catch (Exception ex)
                {
                    XtraMessageBox.Show(ex.Message);
                }
            }
            else
            {
                MsgLog.Items.Add("【" + System.DateTime.Now.ToString() + "】" + "正在取消开机自动启动...");
                //取消开机自动启动
                RegistryKey akey = Registry.LocalMachine;
                akey = akey.OpenSubKey(@"SOFTWARE\Microsoft\windows\CurrentVersion\Run", true);
                akey.DeleteValue("NetClient", false);
                akey.Close();
                AutoStart_bt.Checked = false;

                //自动启动状态
                XmlDocument doc = new XmlDocument();
                XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "GB2312", null); doc.AppendChild(dec);  //创建一个根节点（一级）  

                XmlElement root = doc.CreateElement("ConfigInfo");
                doc.AppendChild(root);

                XmlElement AuotStart = doc.CreateElement("AutoStart");
                AuotStart.SetAttribute("State", "false");
                root.AppendChild(AuotStart);
                //保存配置文件
                doc.Save(Application.StartupPath + "\\AutoStartConfig.xml");


                MsgLog.Items.Add("【" + System.DateTime.Now.ToString() + "】" + "开机启动取消成功.");
            }
        }

        private void LanMain_Load(object sender, EventArgs e)
        {
            string XmlFilePath = Application.StartupPath + "\\AutoStartConfig.xml";

            if (System.IO.File.Exists(XmlFilePath))
            {

                //创建XML实例
                XmlDocument xmlDoc = new XmlDocument();
                //加载XML文件
                xmlDoc.Load(XmlFilePath);

                //设置要查询的节点
                string XmlPathNode = "//ConfigInfo/AutoStart";
                //获取查询节点的属性值
                if (xmlDoc.SelectSingleNode(XmlPathNode).Attributes["State"].Value.ToString() == "True")
                {
                    AutoStart_bt.Checked = true;

                    Text_ChlintIP.Text = xmlDoc.SelectSingleNode("//ConfigInfo/ServerIP").Attributes["IP"].Value.ToString();
                    Text_CientPort.Value = Convert.ToInt32(xmlDoc.SelectSingleNode("//ConfigInfo/ServerPort").Attributes["Port"].Value.ToString());
                    Text_Time_Hour.Value = Convert.ToInt32(xmlDoc.SelectSingleNode("//ConfigInfo/PostH").Attributes["Hour"].Value.ToString());
                    Text_Time_Minute.Value = Convert.ToInt32(xmlDoc.SelectSingleNode("//ConfigInfo/PostM").Attributes["Minute"].Value.ToString());
                    Text_Time_Second.Value = Convert.ToInt32(xmlDoc.SelectSingleNode("//ConfigInfo/PostS").Attributes["Second"].Value.ToString());

                    //开始定时监听并发送
                    MsgLog.Items.Add("10秒后开始连接服务器!");
                    CheckConnection = true;
                    bt_TimeStop.Enabled = true;
                    bt_TimeStart.Enabled = false;
                    StartLinsts();
                }
                else
                {
                    AutoStart_bt.Checked = false;
                }
            }
            string XmlFilePathCh = Application.StartupPath + "\\BackFilePath.xml";

            if (System.IO.File.Exists(XmlFilePathCh))
            {

                //创建XML实例
                XmlDocument xmlDoc = new XmlDocument();
                //加载XML文件
                xmlDoc.Load(XmlFilePathCh);

                //设置要查询的节点
                string XmlPathNode = "//ConfigInfo/AutoStart";
                //获取查询节点的属性值
                if (xmlDoc.SelectSingleNode(XmlPathNode).Attributes["State"].Value.ToString() == "True")
                {

                    AutoStart.Checked = true;

                    Text_SavePath.Text = xmlDoc.SelectSingleNode("//ConfigInfo/BackFilePath").Attributes["Path"].Value.ToString();
                    Text_ServerIP.Text = xmlDoc.SelectSingleNode("//ConfigInfo/ServerIP").Attributes["IP"].Value.ToString();
                    Text_ServerPort.Value = Convert.ToInt32(xmlDoc.SelectSingleNode("//ConfigInfo/ServerPort").Attributes["Port"].Value);


                    if (xmlDoc.SelectSingleNode("//ConfigInfo/SaveAllFileAndDelfile").Attributes["SaveState"].Value.ToString() == "True")
                    {
                        Check_SaveFileAS.Checked = true;
                    }
                    else
                    {
                        Check_SaveFileAS.Checked = false;
                    }

                    Text_DelFileTime.Value = Convert.ToInt32(xmlDoc.SelectSingleNode("//ConfigInfo/SaveDayFile").Attributes["Days"].Value);
                    DelFileTime.Value = Convert.ToInt32(xmlDoc.SelectSingleNode("//ConfigInfo/DelFileTime").Attributes["Time"].Value);

                    StartListentServer();

                }
                else
                {

                    AutoStart.Checked = false;
                }


            }
            IPHostEntry ipe = Dns.GetHostEntry(Dns.GetHostName());
            //Text_ServerIP.Text = ipe.AddressList[0].ToString();
            Text_ServerIP.Text = Dns.GetHostByName(Dns.GetHostName()).AddressList[0].ToString();
        }
        /// <summary>
        /// 设置文件保存路径
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Bt_SaveBrowser_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                Text_SavePath.Text = folderBrowserDialog1.SelectedPath.ToString();
                StartListent.Enabled = true;
            }
        }
        /// <summary>
        /// 启动监听服务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StartListent_Click(object sender, EventArgs e)
        {
            StartListentServer();
        }
        /// <summary>
        /// 启动监听服务
        /// </summary>
        public void StartListentServer()
        {

            isLis = true;
            Bt_SaveBrowser.Enabled = false;
            StopListent.Enabled = true;
            StartListent.Enabled = false;
            DelFileTime.Enabled = false;
            Check_SaveFileAS.Enabled = false;
            Text_DelFileTime.Enabled = false;
            Text_ServerIP.Enabled = false;
            Text_ServerPort.Enabled = false;

            if (Check_SaveFileAS.Checked)
            {
                ListBox_LogMsg.Items.Add("********文件会按接收的时间保存，并只保留近" + Text_DelFileTime.Value.ToString() + "天的文件********");
            }
            else
            {
                ListBox_LogMsg.Items.Add("********文件会按传输的原始文件名保存，并覆盖已存在的同名文件********");
            }

            Control.CheckForIllegalCrossThreadCalls = false;

            D_ThreadRec _D_ThreadRec = new D_ThreadRec(ThreadRec);
            _D_ThreadRec.BeginInvoke(null, null);
        }
        /// <summary>
        /// 停止监听
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StopListent_Click(object sender, EventArgs e)
        {
            isLis = false;
            Check_SaveFileAS.Enabled = true;
            Text_DelFileTime.Enabled = true;
            DelFileTime.Enabled = true;
            Text_ServerIP.Enabled = true;
            Text_ServerPort.Enabled = true;
            ServerSocket.Close();

            Bt_SaveBrowser.Enabled = true;

            StopListent.Enabled = false;

            if (Text_SavePath.Text != "")
            {
                StartListent.Enabled = true;
            }
        }
        #region 启动监听服务
        /// <summary>
        /// 监听服务函数
        /// </summary>
        private void ThreadRec()
        {
            try
            {
                int port = Convert.ToInt32(Text_ServerPort.Value);
                string strIp = Text_ServerIP.Text;

                IPAddress ip = IPAddress.Parse(strIp);
                IPEndPoint ipe = new IPEndPoint(ip, port);

                ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                ServerSocket.Bind(ipe);
                ServerSocket.Listen(10);

                this.BeginInvoke(new D_UpdateUI_Log(UpdateUI_Log), new object[] { System.DateTime.Now + ":服务器开始监听" + Text_ServerPort.Value.ToString() + "端口！" });
                while (true)
                {
                    // ListBox_LogMsg.Items.Add("开始监听!");
                    if (isLis == true)
                    {
                        try
                        {
                            //阻塞监听至到有新的连接
                            Socket temp = ServerSocket.Accept();

                            IPEndPoint clientip = (IPEndPoint)temp.RemoteEndPoint;
                            //如果连接上
                            if (temp.Connected)
                            {
                                //显示客户端连接状态
                                this.BeginInvoke(new D_UpdateUI_Log(UpdateUI_Log), new object[] { "客户端[" + clientip.Address.ToString() + "]在" + System.DateTime.Now + "连接到服务器！" });
                                StartThreads startThreads = new StartThreads(temp, this, Text_SavePath.Text.Trim(), Check_SaveFileAS.CheckState.ToString());
                                //.....................
                            }
                        }
                        catch (Exception ex)
                        {
                            if (ex.Message != "一个封锁操作被对 WSACancelBlockingCall 的调用中断。")//断开socket时阻塞监听的报错提示
                            {
                                MessageBox.Show(ex.Message);
                            }

                        }
                    }
                    else
                    {

                        ServerSocket.Close();
                        this.BeginInvoke(new D_UpdateUI_Log(UpdateUI_Log), new object[] { System.DateTime.Now + ":停止监听服务！" });
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                this.BeginInvoke(new D_UpdateUI_Log(UpdateUI_Log), new object[] { ex.Message });
            }
        }
        #endregion
        /// <summary>
        /// 更新界面信息
        /// </summary>
        /// <param name="str"></param>
        public void UpdateUI_Log(string str)
        {
            ListBox_LogMsg.Items.Add(str);
            ListBox_LogMsg.TopIndex = ListBox_LogMsg.Items.Count - 1;
            if (ListBox_LogMsg.Items.Count > 200)
            {
                ListBox_LogMsg.Items.Clear();
            }
        }
        /// <summary>
        /// 开始删除过期文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer2_Tick(object sender, EventArgs e)
        {
            //获取计算机当前时间
            int intHour = DateTime.Now.Hour;
            int intMinute = DateTime.Now.Minute;
            int intSecond = DateTime.Now.Second;
            // XtraMessageBox.Show(intHour.ToString() + " " + intMinute.ToString() + " " + intSecond.ToString());

            if (intHour == Convert.ToInt32(DelFileTime.Value) && intMinute == 0 && intSecond == 1 && Check_SaveFileAS.Checked == true)
            {

                ListBox_LogMsg.Items.Add(System.DateTime.Now.ToString() + ":开始删除过期文件...");

                System.IO.DirectoryInfo aDirFile = new System.IO.DirectoryInfo(Text_SavePath.Text);
                System.IO.FileInfo[] aFileList = aDirFile.GetFiles();
                for (int i = 0; i < aFileList.Length; i++)
                {
                    string aFIle = aFileList[i].FullName;
                    if (aFIle.Substring(aFIle.LastIndexOf(".")).ToString().ToLower() != ".SDM")
                    {
                        System.IO.FileInfo file = new System.IO.FileInfo(aFIle);

                        if (Convert.ToInt32(file.CreationTime.ToString("yyyy-MM-dd").Replace("-", "")) < Convert.ToInt32(System.DateTime.Now.AddDays(-1 * Convert.ToInt32(Text_DelFileTime.Value)).ToString("yyyy-MM-dd").Replace("-", "")))
                        {
                            System.IO.File.Delete(aFIle);
                            ListBox_LogMsg.Items.Add("过期文件[" + aFIle + "]文件删除成功.");
                        }
                    }
                    else
                    {
                        ListBox_LogMsg.Items.Add("文件" + aFIle + "为传输临时文件，不要删除，如果需除请手动删除。");
                    }

                }
            }
        }
        /// <summary>
        /// 设置自动启动程序和备份文件参数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AutoStart_Click(object sender, EventArgs e)
        {
            if (AutoStart.Checked)
            {
                if (Text_SavePath.Text != "" && Text_ServerIP.Text != "" && Text_ServerPort.Value > 0)
                {
                    if (MessageBox.Show("是否启用开机自动启动程序，并自动监听端口？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {

                        try
                        {
                            //获取程序的完整路径
                            string dir = System.Windows.Forms.Application.ExecutablePath;
                            //设置开启启动
                            RegistryKey akey = Registry.LocalMachine;
                            akey = akey.OpenSubKey(@"SOFTWARE\Microsoft\windows\CurrentVersion\Run", true);
                            akey.SetValue("NetServer", dir);
                            akey.Close();
                            //设置开机启动参数
                            XmlDocument doc = new XmlDocument();
                            XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "GB2312", null); doc.AppendChild(dec);  //创建一个根节点（一级）  

                            XmlElement root = doc.CreateElement("ConfigInfo");
                            doc.AppendChild(root);

                            //自动启动状态
                            XmlElement AuotStart = doc.CreateElement("AutoStart");
                            AuotStart.SetAttribute("State", "True");
                            root.AppendChild(AuotStart);

                            //存储备份文件保存路径
                            XmlElement BackSavePath = doc.CreateElement("BackFilePath");
                            BackSavePath.SetAttribute("Path", Text_SavePath.Text.Trim().ToString());
                            root.AppendChild(BackSavePath);

                            //存储服务端IP
                            XmlElement ServerIP = doc.CreateElement("ServerIP");
                            ServerIP.SetAttribute("IP", Text_ServerIP.Text);
                            root.AppendChild(ServerIP);

                            //存储监听端口
                            XmlElement ServerPort = doc.CreateElement("ServerPort");
                            ServerPort.SetAttribute("Port", Text_ServerPort.Value.ToString());
                            root.AppendChild(ServerPort);

                            //是否按时间保存文件，并删除过期文件
                            XmlElement DateTimeSaveFileAndDelFile = doc.CreateElement("SaveAllFileAndDelfile");
                            DateTimeSaveFileAndDelFile.SetAttribute("SaveState", Check_SaveFileAS.Checked.ToString());
                            root.AppendChild(DateTimeSaveFileAndDelFile);

                            //保存几天之前的文件
                            XmlElement SaveDayFile = doc.CreateElement("SaveDayFile");
                            SaveDayFile.SetAttribute("Days", Text_DelFileTime.Value.ToString());
                            root.AppendChild(SaveDayFile);

                            //删除过期文件时间
                            XmlElement DelFileDateTime = doc.CreateElement("DelFileTime");
                            DelFileDateTime.SetAttribute("Time", DelFileTime.Value.ToString());
                            root.AppendChild(DelFileDateTime);

                            //保存配置文件
                            doc.Save(Application.StartupPath + "\\BackFilePath.xml");
                            AutoStart.Checked = true;

                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                        }

                    }
                }
                else
                {
                    AutoStart.Checked = false;

                    MessageBox.Show("请查看文件保存路径及其他参数设置是否为空！");
                }

            }
            else
            {
                try
                {
                    XmlDocument doc = new XmlDocument();
                    XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "GB2312", null); doc.AppendChild(dec);  //创建一个根节点（一级）  

                    XmlElement root = doc.CreateElement("ConfigInfo");
                    doc.AppendChild(root);

                    //自动启动状态
                    XmlElement AuotStart = doc.CreateElement("AutoStart");
                    AuotStart.SetAttribute("State", "false");
                    root.AppendChild(AuotStart);
                    //保存配置文件
                    doc.Save(Application.StartupPath + "\\BackFilePath.xml");
                    AutoStart.Checked = true;


                    RegistryKey akey = Registry.LocalMachine;
                    akey = akey.OpenSubKey(@"SOFTWARE\Microsoft\windows\CurrentVersion\Run", true);
                    akey.DeleteValue("NetServer", false);
                    akey.Close();
                    AutoStart.Checked = false;
                    MessageBox.Show("随机启动功能已经关闭！");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

            }
        }
        /// <summary>
        ///  按传输时间另存文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Check_SaveFileAS_Click(object sender, EventArgs e)
        {
            if (Check_SaveFileAS.Checked)
            {

                if (MessageBox.Show("开启按时间另存功能后，将自动开启清理过期文件！\n注意：将会删除文件夹内的所有过期文件！是否启动？", "自动清理提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    Check_SaveFileAS.Checked = true;
                    Text_DelFileTime.Enabled = true;
                    DelFileTime.Enabled = true;
                }
                else
                {
                    Check_SaveFileAS.Checked = false;


                }

            }
            else
            {
                Text_DelFileTime.Enabled = false;
                DelFileTime.Enabled = false;
            }
        }
        #region 扫描局域网IP地址窗体
        /// <summary>
        /// 开始扫描
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (button1.Text == "开 始 扫 描")
                {
                    listView1.Items.Clear(); //清空ListView控件中的项
                    textBox1.Enabled = textBox2.Enabled = false;
                    strIP = "";
                    strflag = textBox1.Text;
                    StartIPAddress = textBox1.Text;
                    EndIPAddress = textBox2.Text;
                    //开始扫描地址
                    intStrat = Int32.Parse(StartIPAddress.Substring(StartIPAddress.LastIndexOf(".") + 1));
                    //终止扫描地址
                    intEnd = Int32.Parse(EndIPAddress.Substring(EndIPAddress.LastIndexOf(".") + 1));
                    //指定进度条最大值
                    progressBar1.Maximum = intStrat;
                    //指定进度条最小值
                    progressBar1.Minimum = intEnd;
                    //指定进度条初始值
                    progressBar1.Value = progressBar1.Minimum;
                    timer3.Start();
                    button1.Text = "停 止 扫 描";
                    //使用自定义方法StartScan实例化线程对象
                    myThread = new Thread(new ThreadStart(this.StartScan));
                    myThread.Start();   //开始运行扫描IP的线程
                }
                else
                {
                    textBox1.Enabled = textBox2.Enabled = true;
                    button1.Text = "开 始 扫 描";
                    timer3.Stop();
                    //设置进度条的值为最大值
                    progressBar1.Value = intEnd;
                    if (myThread != null)   //判断线程对象是否为空
                    {
                        //判断扫描IP地址的线程是否正在运行
                        //if (myThread.ThreadState == ThreadState.Running)
                        if (myThread.ThreadState == System.Threading.ThreadState.Running)
                        {
                            myThread.Abort();  //终止线程
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }
        /// <summary>
        /// 扫描局域网IP地址
        /// </summary>
        private void StartScan()
        {
            //扫描的操作
            for (int i = intStrat; i <= intEnd; i++)
            {
                string strScanIP = StartIPAddress.Substring(0, StartIPAddress.LastIndexOf(".") + 1) + i.ToString();
                //转换成IP地址
                IPAddress myScanIP = IPAddress.Parse(strScanIP);
                strflag = strScanIP;
                try
                {
                    //获取DNS主机信息
                    IPHostEntry myScanHost = Dns.GetHostEntry(myScanIP);

                    //获取主机名
                    string strHostName = myScanHost.HostName.ToString();
                    if (strIP == "")
                    {
                        strIP += strScanIP + "->" + strHostName;
                    }
                    else
                    {
                        strIP += "," + strScanIP + "->" + strHostName;
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message.ToString());
                }
            }
        }

        private void LanMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (myThread != null)   //判断线程对象是否为空
            {
                //判断扫描IP地址的线程是否正在运行
                if (myThread.ThreadState == System.Threading.ThreadState.Running)
                {
                    myThread.Abort();  //终止线程
                }
            }
        }

        private void timer3_Tick(object sender, EventArgs e)
        {
            if (strIP != "")     //判断是否有可用的IP地址
            {
                if (strIP.IndexOf(',') == -1)
                {
                    if (listView1.Items.Count > 0)
                    {
                        for (int i = 0; i < listView1.Items.Count; i++)
                        {
                            //判断扫描到的IP地址是否与列表中的重复
                            if (listView1.Items[i].Text != strIP)
                            {
                                //向列表中添加扫描到的已用IP地址
                                listView1.Items.Add(strIP);
                            }
                        }
                    }
                    else
                    {
                        //向列表汇总添加扫描到的已用IP地址
                        listView1.Items.Add(strIP);
                    }
                }
                else
                {
                    string[] strIPS = strIP.Split(',');
                    for (int i = 0; i < strIPS.Length; i++)
                    {
                        listView1.Items.Add(strIPS[i].ToString());
                    }
                }
                strIP = "";
            }
            for (int i = 0; i < listView1.Items.Count; i++)
                listView1.Items[i].ImageIndex = 0;
            if (progressBar1.Value < progressBar1.Maximum)  //判断进度条的当前值是否超出其最大值
                progressBar1.Value = Int32.Parse(strflag.Substring(strflag.LastIndexOf(".") + 1));

            if (strflag == textBox2.Text) //判断正在扫描的IP地址是否是结束IP地址
            {
                timer3.Stop();
                textBox1.Enabled = textBox2.Enabled = true;
                button1.Text = "开 始 扫 描";  //设置按钮文本为扫描
                MessageBox.Show("IP 扫 描 结 束！");
            }
        }
     #endregion
    }
}
